package guida.ccf.gzuexaminesystem.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import guida.ccf.gzuexaminesystem.entity.Admin;
import guida.ccf.gzuexaminesystem.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * 重构 Spring Security 的查询用户的方式
 */
@Slf4j
@Service
public class AdminDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminService userService;

    @Override
    public UserDetails loadUserByUsername(String username) {

        try {
            log.info("管理员登录判断方法执行...");
            // 查询用户信息
            LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Admin::getUserName, username);
            Admin user = userService.getOne(lambdaQueryWrapper);
            if (user == null) {
                throw new UsernameNotFoundException("用户名或密码错误!");
            }

            // 查询权限信息
            String roleType = user.getRoleType();

            // 返回
            return new LoginAdmin(user, Collections.singletonList(roleType));
        } catch (Exception e) {
            return null;
        }
    }
}
